<template>
<a-modal :visible="visible" :title="calcTitle" width="1000px" @cancel="visible = false" @click="submit">
  <a-row>
    <a-col :span="16">
      <entity-view ref="form" :operatorType="operatorType" :model="beanInfo" form-item-width="100%"
                   :labelCol="{span:4}" :wrapperCol="{span:14}" :rules="rules" @submit="submit">
        <form-item label="广告类型" prop="adType" input-type="select" v-model="beanInfo.adType" :disabled="disabled"
                   :options="[
                     {name: '商户服务轮播广告', value: '00'},
                     {name: '交易成功推送广告', value: '01'},
                   ]" @change="adTypeChange"></form-item>
        <form-item label="营销页面地址：" prop="marketingPagePath">
          <a-input v-model="beanInfo.marketingPagePath" placeholder="示例：http://www.xxx.com" :disabled="disabled"></a-input>
        </form-item>
        <form-item label="生效日期" prop="beginTime" v-model="beanInfo.beginTime" date-format="YYYY-MM-DD" input-type="datepicker" :disabled="disabled" :disabledDate="current => disabledDate({current, maxDate: beanInfo.expireTime})"></form-item>
        <form-item label="失效日期" prop="expireTime" v-model="beanInfo.expireTime" date-format="YYYY-MM-DD" input-type="datepicker" :disabled="disabled" :disabledDate="current => disabledDate({current, minDate: beanInfo.beginTime})"></form-item>
        <form-item label="机构名称" prop="orgList">
          <a-tree-select
            treeDataSimpleMode
            v-model="beanInfo.orgList"
            style="width: 100%"
            :tree-data="treeData"
            tree-checkable
            placeholder="请选择参与机构"
            :showCheckedStrategy="SHOW_PARENT"
            :getPopupContainer="() => $refs.treeContainer"
            @change="setOrgInfo"
            :disabled="disabled"
          />
          <div ref="treeContainer" style="position: relative;max-height: 300px;">

          </div>
        </form-item>
        <form-item label="广告描述" prop="adDesc" v-model="beanInfo.adDesc" input-type="textarea" :disabled="disabled"></form-item>
        <form-item label="商户名称" prop="merchantList" :wrapper-col="{span: 20}">
          <merchant-selector
            ref="merchantSelector"
            v-model="beanInfo.merchantList"
            :checked-org-info="checkedOrgInfo"
            @uploaded="templateUploaded"
            :hasUploaded="beanInfo.hasUploaded"
            :disabled="disabled"></merchant-selector>
        </form-item>
        <form-item label="商圈名称" prop="circleList">
          <a-row type="flex" justify="space-between" v-for="(i,index) in beanInfo.circleList" :key="i.mchntNo">
            <a-col :span="20">{{ i.mchntName }}({{i.mchntNo}})</a-col>
            <a-col :span="4"><a href="javascript:" @click="deleteMerchantInfo('circleList', index)" v-if="!disabled">删除</a></a-col>
          </a-row>
          <a-row type="flex" justify="space-between" align="bottom" v-if="!disabled">
            <a-col :span="19">
              <a-textarea placeholder="请输入商圈编号" v-model="beanInfo.merchantCircleRows"></a-textarea>
            </a-col>
            <a-col :span="4">
              <a href="javascript:" @click="getBusinessArea">确定</a>
            </a-col>
          </a-row>
          <div class="tip">
            请输入商圈编号，一行一个，最多输入10个<br>
            已录入{{ beanInfo.circleList.length }}个商圈
          </div>
        </form-item>
        <form-item label="模板" prop="pushAdModule" v-model="beanInfo.pushAdModule" input-type="radioGroup"
                   :disabled="disabled"
                   v-if="beanInfo.adType === '01'"
                   :wrapper-col="{span: 18}"
                   style="width: 100%"
                   :options="[
                    {label: '模板一', value: '01'},
                    {label: '模板二', value: '02'},
                    {label: '模板三', value: '03'},
                    {label: '模板四', value: '04'},
                  ]" @change="createPushSuccessAdImages"></form-item>
        <a-form-model-item label="图片上传" :style="'width: 100%'" :wrapper-col="{span: 18}" prop="images">
          <a-row>
            <a-col :span="24" style="color: #f1545d">注：图片只能上传png、jpg、jpeg、bmp格式且最大支持5M</a-col>
          </a-row>
          <template v-if="beanInfo.adType === '00'">
            <a-row type="flex" justify="space-between" align="middle" v-for="(i,index) in merchantAdImages" :key="i.key" class="image-info">
              <a-col :span="7">
                <div class="img-box">
                  <a-upload
                    accept="image/png, image/jpeg"
                    :name="'img' + (index + 1)"
                    :disabled="disabled"
                    list-type="picture-card"
                    class="avatar-uploader"
                    :file-list="i.fileList"
                    @preview="preview"
                    :before-upload="file => beforeUpload(file, index, 'merchantAdImages')"
                    :customRequest="info => {
                      customUpload(info, index, 'merchantAdImages');
                    }"
                    @change="info => {
                      uploadChange(info, index, 'merchantAdImages');
                    }"
                  >
                    <div v-if="i.fileList.length < 1">
                      <a-icon type="plus" />
                      <div class="ant-upload-text">
                        上传图片
                      </div>
                    </div>
                  </a-upload>
                </div>
              </a-col>
              <a-col :span="7">
                <a-space>
                  <span>顺序号：</span>
                  <a-input-number :min="1" disabled v-model="i.imgNo" style="width:50px;"></a-input-number>
                </a-space>
              </a-col>
              <a-col :span="7">
                <a-space>
                  <a-input-number :min="1" v-model="i.imgTm" style="width:50px;" :disabled="disabled"></a-input-number>
                  <span>秒</span>
                </a-space>
              </a-col>
              <a-col :span="3">
                <a-button type="danger" @click="removeAdImage('merchantAdImages', index)" v-if="!disabled">删除</a-button>
              </a-col>
            </a-row>
          </template>
          <template v-if="beanInfo.adType === '01'">
            <a-row type="flex" justify="space-between" align="middle" v-for="(i,index) in pushSuccessAdImages" :key="i.key" class="image-info" v-if="i.show">
              <a-col :span="7">
                <div class="img-box">
                  <a-upload
                    accept="image/png, image/jpeg"
                    :name="'img' + (index + 1)"
                    list-type="picture-card"
                    class="avatar-uploader"
                    :file-list="i.fileList"
                    :disabled="disabled"
                    @preview="preview"
                    :before-upload="file => beforeUpload(file, index, 'pushSuccessAdImages')"
                    :customRequest="info => {
                      customUpload(info, index, 'pushSuccessAdImages');
                    }"
                    @change="info => {
                      uploadChange(info, index, 'pushSuccessAdImages');
                    }"
                  >
                    <div v-if="i.fileList.length < 1">
                      <a-icon type="plus" />
                      <div class="ant-upload-text">
                        上传图片
                      </div>
                    </div>
                  </a-upload>
                </div>
              </a-col>
              <a-col :span="7">
                <a-space>
                  <span>顺序号：</span>
                  <a-input-number :min="1" disabled v-model="i.imgNo" style="width:50px;"></a-input-number>
                </a-space>
              </a-col>
              <a-col :span="7">
                <a-space>
                  <a-input-number :min="1" v-model="i.imgTm" style="width:50px;" :disabled="disabled"></a-input-number>
                  <span>秒</span>
                </a-space>
              </a-col>
              <a-col :span="3">
                <a-button type="danger" @click="removeAdImage('pushSuccessAdImages', index)" v-if="!disabled">删除</a-button>
              </a-col>
            </a-row>
          </template>
        </a-form-model-item>
      </entity-view>
    </a-col>
    <a-col :span="8">
      <div class="phone-preview">
        <div class="phone-bg">
          <div class="visible-area">
            <div class="content">
              <div class="full-width double-height"></div>
              <div class="half-width"></div>
              <div class="half-width"></div>
              <div class="full-width radius-border"></div>
              <div class="small-block full-width">
                <div></div>
                <div></div>
                <div></div>
                <div></div>
                <div></div>
                <div></div>
              </div>
              <a-carousel autoplay class="swiper full-width double-height">
                <template v-if="beanInfo.adType === '00'">
                  <div class="swiper-slide" v-for="i in merchantAdImages" key="imageLocalPath">
                    <img v-if="i.fileList[0] && (i.fileList[0].url || i.fileList[0].thumbUrl)" :src="i.fileList[0].url || i.fileList[0].thumbUrl" alt="ad">
                  </div>
                </template>
                <template v-else>
                  <div class="swiper-slide" v-for="i in pushSuccessAdImages" key="imageLocalPath" v-if="i.show">
                    <img v-if="i.fileList[0] && (i.fileList[0].url || i.fileList[0].thumbUrl)" :src="i.fileList[0].url || i.fileList[0].thumbUrl" alt="ad">
                  </div>
                </template>
              </a-carousel>
              <div style="height: 10px; margin: 10px auto;"></div>
            </div>
          </div>
        </div>
      </div>
    </a-col>
  </a-row>
  <template v-slot:footer>
    <a-space>
      <a-button type="primary" v-if="(operatorType === 'add' || operatorType === 'edit')" @click="submit">保存</a-button>
      <a-button type="primary" v-if="operatorType === 'examine'" @click="examine(true)">审核通过</a-button>
      <a-button type="primary" v-if="operatorType === 'examine'" @click="examine(false)">审核拒绝</a-button>
      <a-button type="primary" v-if="operatorType === 'release'" @click="release(true)">发布</a-button>
      <a-button type="primary" @click="visible = false">取消</a-button>
    </a-space>
  </template>
  <a-modal :visible="previewVisible" :footer="null" @cancel="previewVisible = false">
    <img alt="example" style="width: 100%" :src="previewImage" />
  </a-modal>
</a-modal>
</template>

<script>

import FormItem from '../../../../../components/common/entityView/FormItem'
import EntityView from '../../../../../components/common/entityView/EntityView'
import MerchantSelector from '@/views/bizimpl/upmp/market/cashierManager/MerchantSelector'
import { TreeSelect } from 'ant-design-vue';
import moment from 'moment'
const SHOW_PARENT = TreeSelect.SHOW_PARENT;

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}
let loadingLock = false
let pIdCache = []

const getChildNodes = (nodes, treeObj) => {
  let childNodes = []
  nodes.forEach(node => {
    if (typeof node === 'string') {
      node = treeObj[node]
    }
    if (node && !pIdCache.includes(node.pId)) {
      const filterNodes = Object.values(treeObj).filter(i => i.pId === node.id)
      if (filterNodes.length) {
        childNodes.push(...filterNodes)
        pIdCache.push(node.id)
        childNodes.push(...getChildNodes(filterNodes, treeObj))
      }
    }
  })
  return childNodes
}
const getParentNodes = (nodes, treeObj) => {
  let parentNodes = []
  nodes.forEach(node => {
    if (typeof node === 'string') {
      node = treeObj[node]
    }
    if (node && node.pId && node.pId !== '999999999' && pIdCache.includes(node.pId) === false) {
      pIdCache.push(node.pId)
      const filterNodes = Object.values(treeObj).filter(i => i.id === node.pId)
      if (filterNodes.length) {
        parentNodes.push(...filterNodes)
        parentNodes.push(...getParentNodes(parentNodes, treeObj))
      }
    }
  })
  return parentNodes
}
const beanInfoInitData = {
  adType: '',
  marketingPagePath: '',
  adDesc: '',
  beginTime: null,
  expireTime: null,
  merchantList: [],
  circleList: [],
  pushAdModule: '01',
  hasUploaded: false,
  mrctFilePath: '',
  orgList: [],
}
export default {
  name: 'MarketingAdsOperation',
  components: {
    FormItem,
    EntityView,
    MerchantSelector
  },
  data() {
    const imagesValidator = (rule, val, cb ) => {
      let images
      if (this.beanInfo.adType === '00') {
        images = this.merchantAdImages
      } else if (this.beanInfo.adType === '01') {
        images = this.pushSuccessAdImages.filter(i => i.show)
      }

      let isAllEmpty = true
      let hasEmptyImgTm = false
      let emptyImgIndex = null
      let showImageLength = 0
      images.map((i, n) => {
        if (i.fileList.length) {
          isAllEmpty = false
          if (!i.imgTm) {
            hasEmptyImgTm = true
          }
        }
        // 判断是否是推送广告类型。并且轮播队列不能为空
        if (this.beanInfo.adType === '01') {
          if (i.fileList.length === 0) {
            emptyImgIndex = n
          }
          showImageLength = n
        }
      })
      if (isAllEmpty) {
        cb(new Error('请最少上传一张图片'))
      } else if (hasEmptyImgTm) {
        cb(new Error('请输入图片轮播间隔时间'))
      } else if (emptyImgIndex !== null && emptyImgIndex < showImageLength) {
        cb(new Error('请完善图片轮播配置队列，或者点击右侧的删除按钮删除此行图片轮播配置'))
      } else {
        cb()
      }
    }
    return {
      SHOW_PARENT,
      visible: false,
      operatorType: 'add',
      beanInfo: beanInfoInitData,
      treeData: [],
      rules: {
        adType: [{required: true, message: '请选择广告类型', trigger: 'change'}],
        marketingPagePath: [{required: true, message: '请输入营销页面地址', trigger: 'blur'}],
        beginTime: [{required: true, message: '请选择生效日期', trigger: 'change'}],
        expireTime: [{required: true, message: '请选择失效日期', trigger: 'change'}],
        adDesc: [{required: true, message: '请输入广告描述', trigger: 'blur'}],
        images: [{required: true, validator: imagesValidator, trigger: 'change'}],
      },
      merchantAdImages: [], // 商户广告图片
      pushSuccessAdImages: [], // 推送成功的广告图片
      previewVisible: false,
      previewImage: '',
      checkedOrgInfo: [],
    }
  },
  computed: {
    calcTitle() {
      let title = '广告';
      switch (this.operatorType) {
        case 'edit':
          title = '编辑' + title;
          break;
        case 'view':
          title = '查看' + title;
          break;
        case 'add':
          title = '新增' + title;
          break;
        case 'release':
          title = '发布' + title;
          break;
      }
      return title
    },
    treeObj () {
      return this.treeData.reduce((i, next) => {
        i[next.id] = next
        return i
      }, {})
    },
    disabled () {
      return this.operatorType === 'view' || this.operatorType === 'release'
    }
  },
  methods: {
    async initTreeData() {
      try {
        const res = await this.$get('/admin/market/cashierManager/getOrgList');
        this.treeData = (res.data || []).map(i => {
          i.id = i.orgCode
          i.orgId = i.orgCode
          i.value = i.orgCode
          i.label = i.orgName
          i.pId = i.superOrgCode
          return i
        });
        if (this.operatorType === 'edit' && this.visible) {
          this.setOrgInfo()
        }
      } catch (e) {
        console.error(e)
        this.$message.error('获取机构树失败');
      }
    },
    show (type, beanInfo) {
      this.operatorType = type;
      this.beanInfo = Object.assign({}, beanInfoInitData, beanInfo)
      this.visible = true;
      try {
        switch (type) {
          case 'add':
            this.pushSuccessAdImages = []
            this.merchantAdImages = []
            break;
          case 'view':
          case 'release':
          case 'edit':
            if (this.beanInfo.imagesInfo) {
              const key = this.beanInfo.adType === '00' ? 'merchantAdImages' : 'pushSuccessAdImages'
              this[key] = this.beanInfo.imagesInfo.map((i,n) => {
                i.src && this.getBase64Image(key, n, i.src, i.id)
                return {
                  key: i.id,
                  fileList: i.src ? [{
                    uid: i.id,
                    name: 'image.png',
                    status: 'done',
                  }]: [],
                  imgNo: i.id,
                  imgTm: i.imgTm,
                  imageLocalPath: i.src,
                  dataId: i.dataId,
                  show: !!i.src
                }
              })
            }
            if (this.beanInfo.orgList && this.beanInfo.orgList.length) {
              this.setOrgInfo()
            }
            this.$nextTick(async () => {
              this.$refs.form.clearValidate();
              if (this.beanInfo.merchantNoRows) {
                await this.$refs.merchantSelector.getMerchants(this.beanInfo.merchantNoRows, async () => {
                  return await this.$postJson(`/admin/merParam/marketingAds/getMerchanListNtc?mchntNo=${this.beanInfo.merchantNoRows}&mchntType=0`)
                })
              }
              if (this.beanInfo.merchantCircleRows) {
                await this.getBusinessArea()
              }
            })
            break;
        }
      } catch (e) {
        console.error(e)
      }
    },
    hide () {
      this.visible = false;
    },
    async getBusinessArea () {
      if (this.beanInfo.orgList.length === 0) {
        this.$message.error('请先选择参与机构');
        return
      }
      if (!this.beanInfo.merchantCircleRows || !this.beanInfo.merchantCircleRows.trim()) {
        this.$message.error('请输入商圈！');
        return
      }
      let merchantCircleList = this.beanInfo.merchantCircleRows.split('\n').filter(i => i.trim())
      if (merchantCircleList.length > 10) {
        this.$message.error('最多输入10个商户号！');
        return
      }
      // 去重
      merchantCircleList = [...new Set(merchantCircleList)]
      // 与之前输入的商户号对比去重
      let oldMerchantCircleList = this.beanInfo.circleList.map(i => i.mchntNo)
      merchantCircleList = merchantCircleList.filter(i => !oldMerchantCircleList.includes(i))
      if (merchantCircleList.length === 0) {
        this.$set(this.beanInfo, 'merchantCircleRows', '')
        this.$message.error('请输入新的商圈！');
        return
      }
      const hide = this.$message.loading('正在查询商圈信息...', 0);
      try {
        const res = await this.$postJson(`/admin/merParam/marketingAds/getMerchanListNtc?mchntNo=${merchantCircleList.join(',')}&mchntType=1`)
        if (res.data.code === '100000') {
          let successData = res.data.data.successData || []
          // 特殊费率的商户也可以添加
          const feeMchntObj = res.data.data.feeMchntData;
          if (feeMchntObj) {
            successData = successData.concat(feeMchntObj);
          }
          const errorData = res.data.data.errorData
          if (errorData && errorData.length > 0) {
            this.$notification.error({
              message: '提示',
              description: `录入的商圈/商户编号：${errorData.map(i => i.mchntNo).join(',')}存在错误，请重新输入！`,
              duration: 0
            });
          }
          const orgMchntData = res.data.data.orgMchntData;
          if (orgMchntData && orgMchntData.length > 0) {
            this.$notification.error({
              message: '提示',
              description: `输入的商户或商圈内的商户所属的机构与已选的机构不符,${orgMchntData.map(i => i.mchntNo).join(',')}不符合要求，请重新输入！`,
              duration: 0
            });
          }
          if (successData.length) {
            this.$set(this.beanInfo, 'circleList', this.beanInfo.circleList.concat(successData))
          }
          this.$set(this.beanInfo, 'merchantCircleRows', '')
        } else {
          this.$message.error(res.data.message);
        }
      } catch (e) {
        this.$message.error('获取商户失败');
        console.error(e)
      }
      hide()
    },
    deleteMerchantInfo (key, index) {
      this.$confirm({
        title: '提示',
        content: '确定删除该商户？',
        okText: '确定',
        cancelText: '取消',
        onOk: () => {
          this.beanInfo[key].splice(index, 1)
          this.$set(this.beanInfo, key, this.beanInfo[key])
        }
      })
    },
    async customUpload (info, index, imageKey) {
      const formData = new FormData()
      formData.append(`imgFile`, info.file)
      formData.append('instId', this.beanInfo.instId)
      formData.append('imageIndex', index + 1)
      formData.append('fileType', '05')
      formData.append('dir', 'image')
      try {
        const res = await this.$upload(`/admin/mcmp/bMchntImageInfo/uploadBomp`, formData)
        if (res.data.code === '100000') {
          const imageInfo = this[imageKey][index]
          imageInfo.fileList.length &&  (imageInfo.fileList[0].status = 'done')
          this.$set(this[imageKey], index, Object.assign({}, imageInfo, {
            imageLocalPath: res.data.data.imageLocalPath,
          }))
        } else {
          this.$message.error(res.data.message);
        }
      } catch (e) {
        this.$message.error('上传图片失败');
        console.error(e)
      }
    },
    async submit () {
      console.log(this.beanInfo.merchantList)
      if (this.beanInfo.merchantList && this.beanInfo.merchantList.length && (!this.beanInfo.orgList || !this.beanInfo.orgList.length)) {
        this.$message.error('在商户信息不为空的情况下，参与机构不可以为空');
        return
      }
      if (loadingLock) {
        this.$message.error('保存中，请勿重复点击');
        return
      }
      let hideLoading
      try {
        await this.$refs.form.validate()
        hideLoading = this.$message.loading('正在提交...', 0)
        const params = JSON.parse(JSON.stringify(this.beanInfo))
        if (this.operatorType === 'add') {
          params.optFlag = 'add'
        } else if (this.operatorType === 'edit') {
          params.optFlag = 'upd'
        }
        if (params.beginTime) {
          params.beginTime = moment(params.beginTime).format('YYYYMMDD')
        }
        if (params.expireTime) {
          params.expireTime = moment(params.expireTime).format('YYYYMMDD')
        }
        params.imgSrc = []
        params.imgThumbSrc = []
        params.imgTm = []
        params.imgNo = []
        params.dataId = []
        if (params.adType === '00' && this.merchantAdImages.length) {
          this.merchantAdImages.filter(i => i.fileList.length).map(i => {
            params.imgSrc.push(i.imageLocalPath)
            params.imgThumbSrc.push(i.imageLocalPath)
            i.imgTm && params.imgTm.push(i.imgTm)
            params.imgNo.push(i.imgNo)
            i.dataId && params.dataId.push(i.dataId)
          })
        } else if (params.adType === '01' && this.pushSuccessAdImages.length) {
          this.pushSuccessAdImages.filter(i => i.show).map(i => {
            params.imgSrc.push(i.imageLocalPath)
            params.imgThumbSrc.push(i.imageLocalPath)
            i.imgTm && params.imgTm.push(i.imgTm)
            params.imgNo.push(i.imgNo)
            i.dataId && params.dataId.push(i.dataId)
          })
        }
        if (params.imgSrc.length === 0) {
          this.$message.error('请最少上传一张广告图片！')
          return
        }
        if (params.imgTm.find(i => !i)) {
          this.$message.error('请填写广告轮播秒数！')
          return
        }
        if (params.orgList) {
          params.orgInfoList = this.checkedOrgInfo.map(i => i.orgId)
          delete params.orgList
        }
        if (params.merchantList && params.merchantList.length) {
          params.merchantList = params.merchantList.map(i => i.mchntNo)
        }
        if (params.circleList && params.circleList.length) {
          params.circleList = params.circleList.map(i => i.mchntNo)
        }
        loadingLock = true
        const res = await this.$postJson('admin/merParam/marketingAds/edit', params)
        if (res.data.code === '100000') {
          this.$message.success('保存成功！');
          this.hide()
          this.$emit('refresh')
        } else {
          this.$message.error(res.data.message);
        }
        hideLoading()
        loadingLock = false
      } catch (e) {
        if (e !== false) { // e 为 folse 时是表单验证不通过
          this.$message.error('保存失败');
        }
        console.error(e)
        hideLoading && hideLoading()
        loadingLock = false
      }
    },
    async examine() {},
    release() {
      const params = {
        instId: this.beanInfo.instId,
        adType: this.beanInfo.adType,
        marketingPagePath: this.beanInfo.marketingPagePath,
        mainDataId: this.beanInfo.mainDataId,
      }
      const hide = this.$message.loading('正在发布...', 0)
      this.$postJson(`admin/merParam/marketingAds/release?instId=${params.instId}&adType=${params.adType}&marketingPagePath=${params.marketingPagePath}&mainDataId=${params.mainDataId}`).then(res => {
        if (res.data.code === '100000') {
          this.$message.success('发布成功！');
          this.hide()
          this.$emit('refresh')
        } else {
          this.$message.error(res.data.message);
        }
      }).catch(err => {
        this.$message.error('发布失败！');
      }).finally(hide)
    },
    adTypeChange () {
      this.beanInfo.adType === '01' ? this.createPushSuccessAdImages() : this.createMerchantAdImages()
    },
    async preview (file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    uploadChange ({fileList}, index, imageKey) {
      const imageInfo = this[imageKey][index]
      imageInfo.fileList = fileList
      this.$set(this[imageKey], index, imageInfo)
    },
    beforeUpload (file, index, imageKey) {
      if (file.size <= 1024 * 1024 * 5) {
        return true
      } else {
        this.$message.error('上传图片大小不能超过5M！');
        this.$nextTick(() => {
          this.removeAdImage(imageKey, index)
        })
        return false
      }
    },

    async downloadTemplate () {
      try {
        await this.$download('admin/market/commissionManager/downloadExcel?type=0',{})
      } catch (e) {
        console.error(e)
      }
    },
    async importTemplate () {
      const formData = new FormData()
      const orgList = this.checkedOrgInfo
      if (orgList.length === 0) {
        this.$message.error('请选择参与机构')
        return
      }
      const fileInput = document.createElement('input')
      fileInput.type = 'file'
      fileInput.accept = '.xls,.xlsx'
      fileInput.onchange = async () => {
        const file = fileInput.files[0]
        if (!file) {
          this.$message.error('请选择文件')
          return
        }
        formData.append('excelFile', file)
        try {
          const res = await this.$upload('admin/market/cashierManager/upload', formData)
          if (res.data.code === '100000') {
            this.$message.success('导入成功')
            this.$set(this.beanInfo, 'hasUploaded', true)
            this.$set(this.beanInfo, 'mrctFilePath', res.data.data)
          } else {
            this.$message.error(res.data.message)
          }
        } catch (e) {
          console.error(e)
          this.$message.error('导入失败')
        }
      }
      fileInput.click()
    },
    async getBase64Image(key, index, imageLocalPath, imageId){
      const params = {
        imageLocalPath: imageLocalPath,
        imgId: imageId,
        fileType: "05",
        instId: this.beanInfo.instId,
      };
      try {
        const res = await this.$get("/admin/mcmp/bMchntImageInfo/getBompImg",params);
        if (res.data.code === "100000") {
          const image = this[key][index]
          const file = image.fileList[0]
          file.url = res.data.data.imageData
          this.$set(this[key], index, image)
        } else {
          this.$message.error(res.data.data.respDesc);
        }
      } catch (e) {
        this.$message.error('获取图片失败');
        console.error(e)
      }
    },
    templateUploaded (fileUrl) {
      this.$set(this.beanInfo, 'hasUploaded', true)
      this.$set(this.beanInfo, 'mrctFilePath', fileUrl)
    },
    setOrgInfo () {
      if (Object.keys(this.treeObj).length) {
        // get child node
        let checkedNodes = this.beanInfo.orgList.map(i => this.treeObj[i]).filter(i => !!i)
        pIdCache = []
        checkedNodes = checkedNodes.concat(getChildNodes(this.beanInfo.orgList, this.treeObj))
        pIdCache = []
        checkedNodes = checkedNodes.concat(getParentNodes(this.beanInfo.orgList, this.treeObj))
        checkedNodes = Object.values(checkedNodes.reduce((item, next) => {
          item[next.id] = next
          return item
        }, {}))
        this.checkedOrgInfo = checkedNodes
      }
    },
    removeAdImage (key, index) {
      const images = this[key]
      images.splice(index, 1)
      images.push({
        key: new Date().getTime(),
        fileList: [],
        imgNo: images.length + 1,
        show: images.length < +this.beanInfo.pushAdModule,
      })
      this[key] = images
      this.beanInfo.adType === '00' ? this.createMerchantAdImages() : this.createPushSuccessAdImages()
    },
    createPushSuccessAdImages () {
      const pushSuccessAdImages = this.pushSuccessAdImages.length ? this.pushSuccessAdImages : new Array(4).fill({})
      this.pushSuccessAdImages = pushSuccessAdImages.map((i,n) => {
        return Object.assign({
          key: new Date().getTime() + n,
          fileList: [],
        }, i, {
          show: n < +this.beanInfo.pushAdModule,
          imgNo: n + 1,
        })
      })
    },
    createMerchantAdImages() {
      const merchantAdImages = this.merchantAdImages.length ? this.merchantAdImages : new Array(5).fill({})
      this.merchantAdImages = merchantAdImages.map((i,n) => {
        return Object.assign({
          key: new Date().getTime() + n,
          fileList: [],
        }, i, {
          imgNo: n + 1,
        })
      })
    },
    disabledDate ({current, minDate, maxDate}) {
      minDate = minDate || moment().subtract(1, 'day')
      if (maxDate) {
        return maxDate.isSameOrBefore(current, 'day') || current.isSameOrBefore(minDate, 'day')
      } else {
        return current && current.isSameOrBefore(minDate, 'day')
      }
    }
  },
  mounted () {
    this.initTreeData();
  }
}
</script>
<style scoped>
.phone-preview {
  width: 100%;
}
</style>
<style scoped lang="scss">
.phone-preview {
  width: 100%;
}
.phone-bg {
  background: url("/static/img/appearset_bgc_big.png") no-repeat;
  background-size: contain;
  position: relative;
  width: 100%;
  padding-top: calc(100% * 2);
}
.img-box {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 10px;
}
.image-info {
  margin-bottom: 10px;
}
.visible-area {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  padding: 60px 24px 90px;

  .content {
    display: flex;
    justify-content: space-between;
    padding: 20px;
    flex-wrap: wrap;
    width: 100%;

    &>div {
      margin-top: 10px;
      margin-bottom: 10px;
      background: #ccc;
      width: 20%;
      height: 40px;
    }
    .full-width {
      width: 100%;
    }
    .radius-border {
      border-radius: 100px;
    }
    .half-width{
      width: 40%;
    }
    .double-height {
      height: 80px;
    }
    .small-block {
      display: grid;
      grid-template-columns: 22% 22% 22% 22%;
      grid-template-rows: 40px 40px;
      grid-gap: 10px 4%;
      background: #eaeaea;
      height: auto;

      &>div{
        background: #ccc;
      }
    }
  }

  .swiper-slide {
    width: 100%;
    height: 80px;

    img {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
